<template>
    <div ref="player" class="music-player" 
        :style="{ animationPlayState: state.isPlaying ? 'running' : 'paused' }">
        <!-- 添加音频元素并绑定 ref -->
        <audio ref="audioRef" preload="metadata"></audio>

        <button ref="minimizeBtn" class="minimize-btn" @click="toggleMinimize">
            {{ state.minimized ? '◯' : '−' }}
        </button>

        <div class="album-cover">
            <img :src="currentSong.cover" :alt="currentSong.title" />
            <div class="album-overlay"></div>
        </div>

        <div class="song-info">
            <h3 class="song-title">{{ currentSong.title }}</h3>
            <p class="song-artist">{{ currentSong.artist }}</p>
        </div>

        <div class="progress-container">
            <div class="progress-bar" @click="seek">
                <div class="progress" :style="{ width: state.progressPercent + '%' }"></div>
                <div class="progress-handle" :style="{ left: state.progressPercent + '%' }"></div>
            </div>
            <div class="time-display">
                <span class="current-time">{{ state.currentTime }}</span>
                <span class="total-time">{{ state.totalTime }}</span>
            </div>
        </div>

        <div class="controls">
            <button class="control-btn skip-btn prev-btn" @click="prevSong">❮</button>
            <button class="control-btn play-btn" @click="togglePlay">
              <svg v-if="state.isPlaying" t="1755911405270" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6333" width="200" height="200"><path d="M243.2 208h166.4v608H243.2zM614.4 208h166.4v608h-166.4z" fill="#ffffff" p-id="6334"></path></svg>
              <svg v-else style="margin-left: 3px" t="1755911477029" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6539" width="200" height="200"><path d="M842.24 569.856L248.832 912.384c-44.544 25.6-100.352-6.656-100.352-57.856V169.472c0-51.712 55.808-83.968 100.352-57.856l593.408 342.528c44.544 25.6 44.544 90.112 0 116.224z" fill="#ffffff" p-id="6540"></path></svg>
            </button>
            <button class="control-btn skip-btn next-btn" @click="nextSong">❯</button>
            <button class="control-btn volume-btn">
                {{ getVolumeIcon() }}
                <div class="volume-panel">
                    <input type="range" class="volume-slider" min="0" max="1" step="0.05"
                        v-model.number="state.volume" />
                </div>
            </button>
        </div>
    </div>
</template>

<script setup>
import { findMusicList } from '@/api/musicPlayer';
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';


// 歌曲列表
const songList = ref([]);

// 播放器状态
const state = reactive({
    currentSongIndex: 0,
    isPlaying: false,
    minimized: false,
    progressPercent: 0,
    currentTime: "00:00",
    totalTime: "00:00",
    volume: 1,
    loading: true,
    errorMessage: ''
});

// DOM引用
const audioRef = ref(null);

const player = ref(null);

const minimizeBtn = ref(null);


// 生命周期钩子
onMounted(async () => {
    await findMusicList({ moduleId: '2' }).then(res => {
        if (res.code == 200) {
            songList.value = res.data;

            Object.assign(currentSong, songList.value[state.currentSongIndex])
        }
    })

    // 确保DOM完全加载后再初始化音频
    nextTick(() => {
        loadSong(currentSong);

        // 监听元数据加载完成
        audioRef.value.addEventListener('loadedmetadata', () => {
            state.totalTime = formatTime(audioRef.value.duration);
            state.loading = false;
        });

        // 监听播放时间更新
        audioRef.value.addEventListener('timeupdate', updateProgress);

        // 监听播放结束
        audioRef.value.addEventListener('ended', () => {
            nextSong();
        });

        // 监听错误
        audioRef.value.addEventListener('error', handleError);

        toggleMinimize();
    });
});

// 当前歌曲
const currentSong = reactive({
    title: '',
    cover: '',
    src: '',
    artist: '',
})
const hasAudio = computed(() => audioRef.value !== null);

watch(() => state.currentSongIndex, () => {
    Object.assign(currentSong, songList.value[state.currentSongIndex])
})

// 加载歌曲
function loadSong(song) {
    if (!audioRef.value) {
        handleError(new Error('音频元素未初始化'));
        return;
    }

    state.loading = true;
    state.errorMessage = '';

    try {
        audioRef.value.src = song.src;
        audioRef.value.load();

        // 尝试自动播放，但捕获可能的自动播放限制错误
        audioRef.value.play()
            .then(() => {
                updatePlayState(true);
            })
            .catch(err => {
                handleError(err);
                // 浏览器可能阻止了自动播放，等待用户交互
            });
    } catch (err) {
        handleError(err);
    }
}

// 错误处理
function handleError(err) {
    // console.error("播放错误:", err);
    state.errorMessage = `播放失败: ${err.message || '未知错误'}`;
    state.isPlaying = false;
    state.loading = false;
}

// 播放/暂停切换
function togglePlay() {
    if (!hasAudio.value) {
        handleError(new Error('音频元素未初始化'));
        return;
    }

    if (audioRef.value.paused) {
        audioRef.value.play()
            .then(() => {
                updatePlayState(true);
                state.errorMessage = '';
            })
            .catch(err => {
                handleError(err);
            });
    } else {
        audioRef.value.pause();
        updatePlayState(false);
    }
}

// 更新播放状态
function updatePlayState(isPlaying) {
    state.isPlaying = isPlaying;
}

// 更新进度条
function updateProgress() {
    if (!hasAudio.value) return;

    const percent = (audioRef.value.currentTime / audioRef.value.duration) * 100 || 0;
    state.progressPercent = percent;
    state.currentTime = formatTime(audioRef.value.currentTime);
}

// 点击进度条跳转
function seek(e) {
    if (!hasAudio.value) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const clickPos = (e.clientX - rect.left) / rect.width;
    audioRef.value.currentTime = clickPos * audioRef.value.duration;
}

// 格式化时间
function formatTime(seconds) {
    if (isNaN(seconds) || !isFinite(seconds)) return "00:00";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 上一曲
function prevSong() {
    if (state.loading || !hasAudio.value) return;

    state.currentSongIndex = (state.currentSongIndex - 1 + songList.value.length) % songList.value.length;
    loadSong(songList.value[state.currentSongIndex]);
}

// 下一曲
function nextSong() {
    if (state.loading || !hasAudio.value) return;

    state.currentSongIndex = (state.currentSongIndex + 1) % songList.value.length;
    loadSong(songList.value[state.currentSongIndex]);
}

// 最小化切换
function toggleMinimize() {
    player.value.classList.toggle('minimized');
    state.minimized = !state.minimized;
}

// 获取音量图标
function getVolumeIcon() {
    return state.volume > 0.5 ? '🔊' : state.volume > 0 ? '🔉' : '🔇';
}

// 监听音量变化
watch(() => state.volume, (newVolume) => {
    if (hasAudio.value) {
        audioRef.value.volume = newVolume;
    }
});

</script>

<style scoped>
/* 保持原有样式不变 */
.music-player {
    position: fixed;
    bottom: 10px;
    left: 10px;
    width: 320px;
    background: rgba(18, 18, 24, 0.95);
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(8px);
    color: #fff;
    overflow: hidden;
    transition: all 0.3s ease;
    z-index: 1000;
}

/* 最小化状态 */
.music-player.minimized {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    animation: rotateMinAudio 5s linear infinite;

}

@keyframes rotateMinAudio {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 专辑封面 */
.album-cover {
    width: 100%;
    height: 180px;
    position: relative;
    overflow: hidden;

    &:hover {
        img {
            transform: scale(1.5);
        }
    }
}

.music-player.minimized .album-cover {
    height: 100%;
    border-radius: 50%;
}

.album-cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 20s linear;
}

.music-player.playing .album-cover img {
    transform: rotate(720deg);
}

.album-overlay {
    position: absolute;
    inset: 0;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
}

/* 歌曲信息 */
.song-info {
    padding: 16px;
    text-align: center;
}

.music-player.minimized .song-info {
    display: none;
}

.song-title {
    font-size: 17px;
    font-weight: 600;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.song-artist {
    font-size: 13px;
    color: #b0b0b8;
}

/* 进度条 */
.progress-container {
    padding: 0 16px 8px;
}

.music-player.minimized .progress-container {
    display: none;
}

.progress-bar {
    width: 100%;
    height: 4px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 2px;
    cursor: pointer;
    position: relative;
}

.progress-bar.disabled {
    cursor: not-allowed;
    opacity: 0.5;
}

.progress {
    height: 100%;
    width: 0%;
    background: #3b82f6;
    border-radius: 2px;
}

.progress-handle {
    position: absolute;
    top: 50%;
    left: 0%;
    width: 12px;
    height: 12px;
    background: white;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 8px rgba(59, 130, 246, 0.8);
    opacity: 0;
    transition: opacity 0.2s;
}

.progress-bar:hover .progress-handle {
    opacity: 1;
}

.time-display {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #b0b0b8;
    margin-top: 6px;
}

/* 控制按钮 */
.controls {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12px 16px;
    gap: 18px;
}

.music-player.minimized .controls {
    display: none;
}

.control-btn {
    background: none;
    border: none;
    color: white;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.control-btn:disabled {
    opacity: 0.3;
    cursor: not-allowed;
}

.skip-btn {
    width: 36px;
    height: 36px;
    font-size: 18px;
    opacity: 0.8;
}

.skip-btn:hover:not(:disabled) {
    opacity: 1;
    transform: scale(1.1);
}

.play-btn {
    width: 48px;
    height: 48px;
    background: #3b82f6;
    border-radius: 50%;
    font-size: 20px;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.play-btn:hover:not(:disabled) {
    transform: scale(1.05);
    background: #2563eb;
}

/* 最小化按钮 */
.minimize-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 24px;
    height: 24px;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    border-radius: 50%;
    color: white;
    cursor: pointer;
    font-size: 14px;
    z-index: 10;
}

.minimize-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.music-player.minimized .minimize-btn {
    width: 100%;
    height: 100%;
    top: 0;
    right: 0;
    font-size: 20px;
    background: transparent;
}

/* 音量控制 */
.volume-btn {
    position: relative;
    width: 32px;
    height: 32px;
    font-size: 16px;
    opacity: 0.8;
}

.volume-btn:hover:not(:disabled) {
    opacity: 1;
}

.volume-panel {
    position: absolute;
    right: 0;
    bottom: 40px;
    width: 120px;
    height: 4px;
    border-radius: 2px;
    display: none;
    padding: 8px 0;
}

.volume-btn:hover .volume-panel {
    display: block;
}

.volume-slider {
    width: 100%;
    height: 4px;
    -webkit-appearance: none;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 2px;
    outline: none;
}

.volume-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 12px;
    height: 12px;
    background: white;
    border-radius: 50%;
    box-shadow: 0 0 8px rgba(59, 130, 246, 0.8);
    cursor: pointer;
}

/* 状态和错误消息 */
.status-message,
.error-message {
    padding: 8px 16px;
    text-align: center;
    font-size: 14px;
}

.error-message {
    background: rgba(255, 0, 0, 0.2);
    color: #ff6b6b;
}
</style>